package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
// @CacheConfig(cacheNames = "com.atguigu.gulimall.product.service.impl.CategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查询所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);

        // 2. 将商品三级分类数据转为树形结构
        return list.stream()
                // 2.1 找到所有的一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                // 2.2 递归查找所有菜单的子菜单
                .peek(menu -> menu.setChildren(getChildrens(list, menu)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param all  子菜单
     * @param root 当前菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(List<CategoryEntity> all, CategoryEntity root) {
        return all.stream()
                .filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId()))
                // 查找所有菜单的子菜单
                .peek(categoryEntity -> categoryEntity.setChildren(getChildrens(all, categoryEntity)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        // 1. 检查要删除的菜单是否被别的地方引用
        // TODO
        // 2. 删除菜单，逻辑删除，数据记录的 show_status 字段值，1 表示显示，0 表示隐藏
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> totalPath = findTotalPath(catelogId, paths);

        // findParentPath 方法获取的各级分类对象 ID 集合顺序是 {孙, 子, 父}，需要反转
        Collections.reverse(totalPath);

        return totalPath.toArray(new Long[0]);
    }

    /**
     * 递归查找分类对象的父分类，将当前分类对象 ID 和它的父分类对象 ID 依次添加到集合中
     *
     * @param catelogId 当前分类对象 ID
     * @param paths     各级分类对象 ID 集合
     * @return
     */
    private List<Long> findTotalPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findTotalPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 级联更新所有关联数据
     *
     * @param category
     */
    // @CacheEvict(value = {"category"}, key = "'getLevelOneCategories'")// 清除单个缓存
    // @Caching 支持同时进行多种缓存操作
    @Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevelOneCategories'"),
            @CacheEvict(value = {"category"}, key = "'getCatalogJson'")})
    // @CacheEvict(value = {"category"}, allEntries = true)// 清除指定命名空间的所有缓存
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(CategoryEntity category) {
        // 1. 更新当前分类对象
        this.updateById(category);

        // 2. 更新关联表数据
        if (StringUtils.hasText(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

            // TODO 更新其他关联表数据
        }
    }

    /**
     * 查询所有一级分类
     *
     * @return
     */
    // value 属性值是缓存的前缀，key 属性值是缓存的 key，#root.method.name 表示当前方法的名称，即 getLevelOneCategories
    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevelOneCategories() {
        // return null;
        return this.list(new LambdaQueryWrapper<CategoryEntity>()
                .eq(CategoryEntity::getParentCid, 0));
    }

    /**
     * 获取商品三级分类数据
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        // 查询所有分类
        List<CategoryEntity> allCategoryEntityList = this.list();

        // 获取所有一级分类
        List<CategoryEntity> levelOneCategories = getListByParentCid(allCategoryEntityList, 0L);

        // 封装数据
        return levelOneCategories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    // 获取当前一级分类下的所有二级分类
                    List<CategoryEntity> levelTwoCategories = getListByParentCid(allCategoryEntityList, v.getCatId());
                    List<Catelog2Vo> catelog2VoList = null;
                    if (CollectionUtil.isNotEmpty(levelTwoCategories)) {
                        catelog2VoList = levelTwoCategories.stream().map(level2Entity -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2Entity.getCatId().toString(), level2Entity.getName());
                                    // 为当前 Catelog2Vo 对象设置 catalog3List 属性
                                    List<CategoryEntity> levelThreeCategories = getListByParentCid(allCategoryEntityList, level2Entity.getCatId());
                                    List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                                    if (CollectionUtil.isNotEmpty(levelThreeCategories)) {
                                        catelog3VoList = levelThreeCategories.stream().map(level3Entity -> new Catelog2Vo.Catelog3Vo(level2Entity.getCatId().toString(), level3Entity.getCatId().toString(), level3Entity.getName())).collect(Collectors.toList());
                                    }
                                    catelog2Vo.setCatalog3List(catelog3VoList);
                                    return catelog2Vo;
                                })
                                .collect(Collectors.toList());

                    }
                    return catelog2VoList;
                }
        ));
    }

    /**
     * 根据 parentCid 查询各级别分类集合
     *
     * @param allCategoryEntityList
     * @param parentCid
     * @return
     */
    private List<CategoryEntity> getListByParentCid(List<CategoryEntity> allCategoryEntityList, Long parentCid) {
        return allCategoryEntityList.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

}